package com.haredot.advice;

import com.haredot.interceptor.exception.IpRateException;
import com.haredot.vo.R;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionAdvice {


    @ExceptionHandler({HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class})
    public R<?> exceptionBadRequest(Exception e) {
        return R.fail(R.StatusCode.BAD).build();
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R<?> exceptionBadRequest(NoHandlerFoundException e) {
        return R.fail(80000, "请求地址找不到").build();
    }

    @ExceptionHandler(IpRateException.class)
    public R<?> exceptionBadRequest(IpRateException e) {
        return R.fail(R.StatusCode.FORBIDDEN,  e.getMessage()).build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> exception(MethodArgumentNotValidException e) {
        Map<String, String> reduce = e.getBindingResult().getFieldErrors().stream()
                .reduce(new HashMap<>(), (map, fieldError) -> {
                    map.put(fieldError.getField(), fieldError.getDefaultMessage());
                    return map;
                }, (a, b) -> a);

        return R.fail(R.StatusCode.BAD).data(reduce);
    }

    @ExceptionHandler(Exception.class)
    public R<?> exception(Exception e) {
        e.printStackTrace();
        return R.fail(R.StatusCode.ERROR).build();
    }
}
